﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using MatchDisp.Util;

namespace MatchDisp.MatchIterm
{
    public class ItemContainer
    {
        private List<MatchItem> ItemList = new List<MatchItem>();
        private MatchItem[,] reverseMap = null;
        private System.Drawing.Size boxSize;
        private double scale;

        public ItemContainer(String DataPath, System.Drawing.Size ImageSize, double Scale)
        {
            if ((ImageSize.Height <= 0) || (ImageSize.Width <= 0))
                throw new Exception("Incorrect image size");
            reverseMap = new MatchItem[ImageSize.Height, ImageSize.Width];
            boxSize = DrawingUtil.ScaleSize(ImageSize, Scale);
            scale = Scale;
            
            foreach(String line in File.ReadAllLines(DataPath))
            {
                MatchItem item = new MatchItem(line);
                ItemList.Add(item);
                System.Drawing.Rectangle rect = DrawingUtil.ScaleRect(item.GetPreMatchRect(), Scale);
                for (int y = Math.Max(0, rect.Top); y <= Math.Min(ImageSize.Height - 1, rect.Bottom); y++)
                {
                    for (int x = Math.Max(0, rect.Left); x <= Math.Min(ImageSize.Width - 1, rect.Right); x++)
                        reverseMap[y, x] = item;
                }
            }
        }

        public MatchItem SelectItem(int X, int Y)
        {
            if ((X < boxSize.Width) && (X >= 0) && (Y < boxSize.Height) && (Y >= 0))
                return reverseMap[Y, X];
            else
                return null;
        }
    }
}
